package com.gewe.wxChat.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gewe.wxChat.api.base.LoginApi;
import com.gewe.wxChat.api.base.PersonalApi;
import com.gewe.wxChat.common.BaseResponse;
import com.gewe.wxChat.common.ErrorCode;
import com.gewe.wxChat.common.ResultUtils;
import com.gewe.wxChat.manager.JudgeManager;
import com.gewe.wxChat.model.dto.gewe.TextCallback;

import com.gewe.wxChat.model.entity.WxDevice;
import com.gewe.wxChat.model.entity.WxUser;
import com.gewe.wxChat.manager.strategy.SanZhiStrategy;
import com.gewe.wxChat.model.enums.MsgTypeEnum;
import com.gewe.wxChat.netty.PushMsgServiceImpl;
import com.gewe.wxChat.service.WxDeviceService;
import com.gewe.wxChat.service.SysConfigService;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Resource;

import com.gewe.wxChat.service.WxuserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * app接口
 */
@RestController
@RequestMapping("/wxDevice")
@Slf4j
public class WxDeviceController {
    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private WxDeviceService appService;

    @Resource
    private WxuserService wxuserService;

    @Resource
    private SanZhiStrategy sanZhiManage;
    
    @Resource
    private JudgeManager judgeManager;
    
    @Resource
    private PushMsgServiceImpl pushMsgService;

    private static final Logger logger = LoggerFactory.getLogger(WxDeviceController.class);



    /**
     * 获取登录二维码(创建设备)
     *
     * @return
     */
    @PostMapping("/login/getLoginQrCode")
    public BaseResponse getLoginQrCode(String appId) {
        HashMap<String, Object> map = new HashMap<>();
        JSONObject jsonObject = LoginApi.getQr(appId);
        // 先将第一个get返回的对象转换为JSONObject
//        {"ret":500,"msg":"微信已登录，请勿重复登录。"}
        JSONObject dataObject = jsonObject.getJSONObject("data");
        // 然后使用转换后的JSONObject来获取appId
        String appid = dataObject.getString("appId");
        String uuid = dataObject.getString("uuid");
        LambdaQueryWrapper<WxDevice> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WxDevice::getAppId, appid);
        WxDevice wxDevice = appService.getOne(lambdaQueryWrapper);
        if(wxDevice==null){
            wxDevice=new WxDevice();
            wxDevice.setAppId(appid);
            wxDevice.setUuid(uuid);
            appService.save(wxDevice);
        }else {
            wxDevice.setUuid(uuid);
            appService.updateById(wxDevice);
        }
        

        map.put("appId", appId);
        map.put("uuid", uuid);
        map.put("qrImgBase64", dataObject.getString("qrImgBase64"));
        map.put("qrData", dataObject.getString("qrData"));
        return ResultUtils.success(map);
    }

    /**
     * 检测是否登录成功了
     *
     * @param appid
     * @return
     */
    @PostMapping("/login/checkLogin")
    public BaseResponse checkLogin(String appid, String uuid, String captchCode) {
        JSONObject jsonObject = LoginApi.checkQr(appid, uuid, captchCode);
        logger.info("执行登录(步骤3) 返回结果:" + jsonObject);
        // 先将第一个get返回的对象转换为JSONObject
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject loginInfo = data.getJSONObject("loginInfo");
        if(loginInfo != null){
            String appId = loginInfo.getString("appId");
            if (StringUtils.isNotBlank(appId)) {
                // 然后使用转换后的JSONObject来获取appId
                LambdaQueryWrapper<WxDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(WxDevice::getAppId, appId);
                WxDevice wxDevice = appService.getOne(lambdaQueryWrapper);
                if (wxDevice != null) {
                    wxDevice.setWxId(loginInfo.getString("wxid"));
                    wxDevice.setNickName(loginInfo.getString("nickName"));
                    wxDevice.setMobile(loginInfo.getString("mobile"));
                    wxDevice.setAlias(loginInfo.getString("alias"));
                    appService.updateById(wxDevice);
                }
            }
            return ResultUtils.success(jsonObject);
        }
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, String.valueOf(jsonObject.getJSONObject("msg")));
    }

    @PostMapping("/listApp")
    public BaseResponse<List<WxDevice>> listApp() {
        List<WxDevice> apps = appService.list();
        return ResultUtils.success(apps);
    }
    

    //检测是否在线
    @PostMapping("/checkIsOnline")
    public BaseResponse checkIsOnline(String appId) {
        JSONObject jsonObject = LoginApi.checkOnline(appId);
        if ((Boolean) jsonObject.get("data")) {
            return ResultUtils.success(jsonObject);
        }
        return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR);
    }

    //获取个人信息
    @PostMapping("/getUserInfo")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse getUserInfo(String appId) {
        JSONObject jsonObject = PersonalApi.getProfile(appId);

        if (jsonObject.get("data") != null) {
            //保存用户信息
            WxUser newWxuser = jsonObject.getObject("data", WxUser.class);
            LambdaQueryWrapper<WxUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WxUser::getWxId, newWxuser.getWxId());
            WxUser wxuser = wxuserService.getOne(queryWrapper);
            if (wxuser == null) {
                wxuserService.save(newWxuser);
            } else {
                UpdateWrapper<WxUser> updateWrapper = new UpdateWrapper<>();
                wxuserService.updaetByWxId(newWxuser);
            }
            //查询设备
            LambdaQueryWrapper<WxDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WxDevice::getAppId, appId);
            //更新设备信息
            WxDevice wxDevice = appService.getOne(lambdaQueryWrapper);
            wxDevice.setWxId(newWxuser.getWxId());
            wxDevice.setNickName(newWxuser.getNickName());
            wxDevice.setMobile(newWxuser.getMobile());
            wxDevice.setAlias(newWxuser.getAlias());
            appService.updateById(wxDevice);
            return ResultUtils.success(jsonObject);
        }
        return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
    }

    //回调地址
    @PostMapping("/callback")
    public void callback(@RequestBody HashMap<String, Object> hashMap) {
        

        logger.info("回调接收的信息内容:" + hashMap);
        
//        if(hashMap.get)
        if(ObjectUtils.isNotEmpty(hashMap.get("testMsg")) && ((String)hashMap.get("testMsg")).contains("回调地址链接成功")){
            logger.info("回调地址链接成功:" + hashMap);
            return;
        }
        
        String appid=(String) hashMap.get("Appid");
        String wxId=(String) hashMap.get("Wxid");
        String typeName= (String) hashMap.get("TypeName");
        
        HashMap<String, Object> dataMap = (HashMap<String, Object>) hashMap.get("Data");
        if(dataMap.isEmpty()){
            return;
        }
        //消息类型
        int msgType = (int) dataMap.get("MsgType");
        //判断消息是否是文字类型
        if(msgType != MsgTypeEnum.WX_TEXT.getValue()){
            return;
        }
        
        
        Integer msgId=(Integer) dataMap.get("MsgId");
        String fromUserName=(String)((HashMap<String, Object>) dataMap.get("FromUserName")).get("string");
        String ToUserName=(String) ((HashMap<String, Object>) dataMap.get("ToUserName")).get("string");
        String content= (String) ((HashMap<String, Object>) dataMap.get("Content")).get("string");
        //如果内容体为空，不继续执行
        if(StringUtils.isBlank(content)){
            return;
        }
        Integer createTime=(Integer) dataMap.get("CreateTime");
        Long newMsgId=(Long) dataMap.get("NewMsgId");
        String pushContent= (String) dataMap.get("PushContent");

        TextCallback textCallback=new TextCallback();
        textCallback.setAppId(appid);
        textCallback.setWxId(wxId);
        textCallback.setFromUserName(fromUserName);
        textCallback.setToUserName(ToUserName);
        textCallback.setContent(content);
        textCallback.setCreateTime(createTime);
        textCallback.setNewMsgId(newMsgId);
        
        //这里通过websocket传信息给前端
        
        CompletableFuture<Void> pushFuture = CompletableFuture.runAsync(() -> {
            pushMsgService.pushMsgTofront(appid,wxId, textCallback);
        });
        
        CompletableFuture<Void> judgeFuture = CompletableFuture.runAsync(() -> {
            judgeManager.doJudge(textCallback);
        });
    }

    //退出
    @PostMapping("/logout")
    public BaseResponse logout(String appId) {
        JSONObject jsonObject = LoginApi.logout(appId);
        return ResultUtils.success(jsonObject);
    }
}
